<!-- 需求添加、编辑页面 -->
<template>
  <PageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    <template #footer>
      <AButton type="primary" @click="addDemand"> 提交 </AButton></template
    >
    <div class="title-item">
      <a-space style="margin-left: 40px">
        <div
          style="
            width: 5px;
            height: 23px;
            background-color: rgba(61, 126, 255, 1);
            border: none;
            border-radius: 2px;
          "
        ></div>
        <div>基本信息</div></a-space
      >
    </div>
    <div class="demand-index">
      <AForm
        ref="refForm"
        :model="demand.info"
        autoLabelWidth
        layout="vertical"
      >
        <ARow :gutter="16">
          <ACol
            v-for="element in demandForm?.info?.design?.form"
            :key="element.id"
            :span="element.span"
          >
            <FormItem
              :name="element.name"
              :componentType="element.componentType"
              v-model:props="element.props"
              :required="element.required"
              v-model:values="element.values"
              :disabled="element.disabled"
            />
          </ACol>
        </ARow>
      </AForm>
    </div>
  </PageHeader>

  <!-- <div class="box">
   </div
  > -->
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import {
    getDemandFormStatusOn,
    getOrderDemand,
    postDemandForm,
  } from '@/api/order-management/client-management/demand/demand';
  import * as apilist from '@/api/order-management/client-order/index';
  import { useRouter, useRoute } from 'vue-router';

  const route = useRoute();
  const router = useRouter();
  const breadCrumb: string[] = ['需求管理', '客户需求', '录入订单'];
  const title = ref('录入订单');
  const layout = ref('vertical');
  type Tlayout = 'inline' | 'horizontal' | 'vertical' | undefined;
  const fakeValue = ref(['']);
  const refForm = ref();
  let userData = JSON.parse(sessionStorage.getItem('loginInfo') as any);
  // interface DemandType {
  //   info: {
  //     flow: number;
  //     number: string;
  //     clientCompanyId: number;
  //     userStaffId: number;
  //     extend: string;
  //     orderTime: string;
  //     product: any;
  //     // delivery: any;
  //     orderTemplateId: number;
  //     remark: string;
  //     status: number;
  //   };
  // }
  const demand = reactive<any>({
    info: {
      flow: null, //
      number: '', //编号
      clientCompanyId: null, //客户
      userStaffId: null, //业务经理
      contractId: null, //关联合同id
      customerId: '', //客户联系人id
      extend: '', //扩展
      orderTime: null, //订单时间
      invoiceInformation: '', //收款方式
      payMode: null, //付款方式
      remark: null, //备注
      invoiceId: null,
      orderTemplateId: null, //模板ID
      product: [], //产品详情
      delivery: [], //产品详情
      state: 0,
      collectionAccountId: null,
      file: [],
      processId: null,
    },
  });

  //   储存客户列表数据
  const clientList: any = reactive({
    list: [],
  });
  interface DemandFormType {
    info: {
      id: number;
      flowId: number;
      design: {
        form: any[];
      };
    };
  }
  const demandForm = reactive<DemandFormType>({
    info: { id: 0, flowId: 0, design: { form: [] } },
  });
  const getByTemplateStatusOn = async (id?: any) => {
    if (!id) {
      let res = await getDemandFormStatusOn({ type: 1 });
      demandForm.info = res;
      demandForm.info.design.form.sort((a: any, b: any) => a.sort - b.sort);
      demandForm.info.design.form.forEach((item: any) => {
        // item.disabled = true;
        item.props = JSON.parse(item.props);
        if (item.values !== '') {
          item.values = JSON.parse(item.values);
          if (item.values[0] === '') {
            item.values = [];
          }

          if (item.code === 'CONTRACT_SELECT') {
            item.values[0] = undefined;
          }
          if (item.componentType === 'FILE') {
            item.props.data = demand.info.file;
          }
          if (item.code === 'BUSINESS_MANAGER') {
            item.values = [userData.id];
          }
        }
      });
      demand.info.orderTemplateId = demandForm.info.id;
      demand.info.flow = demandForm.info.flowId;
    } else {
      let res = await getOrderDemand({ id });
      demand.info = res;
      demandForm.info.design.form = JSON.parse(res.extend);
      demandForm.info.design.form.forEach((item: any) => {
        item.disabled = true;
      });
    }
  };
  const keys = Object.keys(demand.info);
  const addDemand = async () => {
    if (!(await refForm.value.validate())) {
      const keys = Object.keys(demand.info);
      demandForm.info.design.form.forEach((item) => {
        if (item.code === 'TABLE') {
          if (route.query.id) {
            demand.info.product = item.props.data;
          } else {
            demand.info.orderProduct = item.props.data;
            demand.info.totalPrice = item.props.totalPrice;
          }
        }
        if (item.code === 'FILE') {
          demand.info.file = item.props.data;
        }
        if (item.code === 'DELIVERY_REQUIREMENTS_BC') {
          if (route.query.id) {
            demand.info.delivery = item.props.data;
            demand.info.delivery.forEach((item: any) => {
              item.items.map((element: any) => {
                element.deliveryTime = new Date(element.deliveryTime).toJSON();
                return element;
              });
            });
          } else {
            demand.info.orderDelivery = item.props.data;
            demand.info.orderDelivery.forEach((item: any) => {
              item.items.map((element: any) => {
                element.deliveryTime = new Date(element.deliveryTime).toJSON();
                return element;
              });
            });
          }
        }
        if (item.fieldName && keys.includes(item.fieldName)) {
          demand.info[item.fieldName] = item.values[0];
        }
      });
      demand.info.extend = JSON.stringify(demandForm.info.design.form);
      delete demand.info.extends;
      demand.info.state = 1;
      demand.info.customerId = Number(demand.info.customerId);
      demand.info.orderTime = new Date(demand.info.orderTime).toJSON();
      if (title.value === '转入订单') {
        await apilist.toClientOrder(demand.info);
        router.push({
          name: 'SalesOrder',
        });
      } else {
        await apilist.addClientOrder(demand.info);
        router.back();
      }
    }
    // 控件对应上字段
  };

  onMounted(() => {
    // 如果是添加则获取状态开启的那个模板
    if (route.query.id) {
      getByTemplateStatusOn(Number(route.query.id));
      title.value = '转入订单';
    } else {
      getByTemplateStatusOn();
      title.value = '录入订单';
    }
  });
</script>

<style scoped lang="less">
  .demand-index {
    padding: 25px 140px;
    width: 95%;
    margin: 0 auto;
    .addClient {
      position: absolute;
      margin-left: 20px;
      margin-top: -15px;
    }
  }

  .success {
    position: absolute;
    right: 30px;
    background-color: #31c27c;
    color: #fff;
    border-radius: 100%;
    width: 50px;
    text-align: center;
  }

  .blacklist {
    position: absolute;
    right: 30px;
    background-color: red;
    color: #fff;
    margin-left: 20px;
    border-radius: 100%;
    width: 50px;
    text-align: center;
  }

  .box {
    padding-top: 10px;
    margin-top: 10px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
  }

  .title-item {
    width: 95%;
    height: 60px;
    margin: auto;
    background-color: rgba(245, 247, 250);
    line-height: 60px;
    margin-top: 20px;
  }
</style>
